#!/usr/bin/env ruby
$:.unshift File.join(File.dirname(__FILE__))
require 'amarok.rb'
require "rexml/document"

SMART_SHUFFLE_ACTION_NAME = "Shuffle"
SMART_SHUFFLE = "Smart Shuffle"
@playlist = Amarok.new 'playlist'
@script = Amarok.new 'script'

@script.add_custom_menu_item(SMART_SHUFFLE, SMART_SHUFFLE_ACTION_NAME)

def cleanup()
  puts( "Script was terminated." )
  @script.remove_custom_menu_item(SMART_SHUFFLE, SMART_SHUFFLE_ACTION_NAME)
  exit
end

trap( "SIGTERM" ) { cleanup }
trap( "SIGINT" ) { cleanup }

############################# DEBUG #######################################

#filename = '/home/matt/.kde/share/apps/amarok/current.xml'
#xml = File.open(filename) {|file| file.read}
#doc = REXML::Document.new xml
#
#playlist_items = retrieve_playlist_items doc
#puts playlist_items
#puts "#{playlist_items.length} items"
#puts "\n\n"
#shuffled = smart_shuffle playlist_items
#puts shuffled
#exit
############################## SCRIPT LOOP ################################
loop do
  message = gets().chomp()
  puts "message: #{message}"
  command = /[A-Za-z]*/.match(message).to_s

  case command
  when "configure"
    msg  = '"This script does not have configuration options."'
    @playlist.popup_message msg

  when "fetchLyrics"
    args = message.split
    artist = args[1]
    title  = args[2]
    puts "no capability for lyrics as of now"

  when "customMenuClicked"
    filename = @playlist.save_current_playlist
    xml = File.open(filename) {|file| file.read}
    doc = REXML::Document.new xml

    playlist_items = retrieve_playlist_items doc
    shuffled = smart_shuffle playlist_items

    @playlist.clear_playlist
    shuffled.each {|item|
      @playlist.add_media item.kurl
    }
  end
end
